<template>
	<div>
		<div class="topTitle">兑换码管理</div>
		<el-form inline :model="query" label-width="auto">
			<el-form-item label="名称">
				<el-input v-model="query.title" placeholder="请输入名称" class="width260 margin-right10"></el-input>
			</el-form-item>
			<el-form-item label="兑换类型">
				<el-select placeholder="请选择兑换类型" class="width260 margin-right10" v-model="query.type" clearable>
					<el-option label="商品兑换" :value="1"></el-option>
					<el-option label="专题兑换" :value="2"></el-option>
					<el-option label="机构兑换" :value="4"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="状态">
				<el-select placeholder="请选择状态" class="width260 margin-right10" v-model="query.status" clearable>
					<el-option label="正常" :value="1"></el-option>
					<el-option label="禁用" :value="0"></el-option>
					<el-option label="已结束" :value="2"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="创建时间">
				<el-date-picker v-model="dateTime" type="datetimerange" range-separator="至" start-placeholder="开始时间"
					end-placeholder="结束时间" class="margin-right20" value-format="yyyy-MM-dd HH:mm:ss" @change="onDateChange">
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleSearch">搜索</el-button>
				<el-button @click="handleRefresh">重置</el-button>
			</el-form-item>
		</el-form>
		<div class="margin-top20 margin-bottom20">
			<el-button type="primary" @click="addVisible=true">新建</el-button>
		</div>
		<el-table :data="tableData" border header-cell-class-name="table-header-style">
			<el-table-column type="selection" width="80" align="center"></el-table-column>
			<el-table-column prop="title" label="兑换码名称" align="center"></el-table-column>
			<el-table-column prop="type" label="兑换码类型" align="center">
				<template slot-scope="{row}">
					<span v-if="row.type==1">商品兑换</span>
					<span v-else-if="row.type==2">专题兑换</span>
					<span v-else-if="row.type==4">机构兑换</span>
				</template>
			</el-table-column>
			<el-table-column prop="codeComment" label="兑换内容" align="center"></el-table-column>
			<el-table-column prop="status" label="兑换码状态" align="center">
				<template slot-scope="scope">
					<span v-if="scope.row.status==0">未开始</span>
					<span v-else-if="scope.row.status==1">进行中</span>
					<span v-else-if="scope.row.status==2">已结束</span>
					<span v-else-if="scope.row.status==3">已失效</span>
				</template>
			</el-table-column>
			<el-table-column label="有效时间" align="center" width="300">
				<template slot-scope="{row}">
					<div v-if="row.validation==1">长期有效</div>
					<div v-else-if="row.validation==2" class="row-me row-center">
						<span>{{row.startTime||''}}</span><span class="margin-left5 margin-right5">-</span>
						<span>{{row.endTime||''}}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="已使用/总量" align="center">
				<template slot-scope="scope">
					{{scope.row.endCount||0}}/{{scope.row.count||0}}
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
			<el-table-column label="操作" width="200" align="center">
				<template slot-scope="scope">
					<el-button type="text" @click="clickCode(scope.row)">码库</el-button>
					<el-button type="text" @click="handleLock(scope.row)">使失效</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="margin-top10">
			<el-pagination background layout="->,total,sizes, prev, pager, next" :page-sizes="[30, 40, 50, 60]"
				@size-change="handleSizeChange" :current-page="query.pageNumber" :total="pageTotal"
				@current-change="handlePageChange"></el-pagination>
		</div>

		<!-- 码库 -->
		<el-dialog title="码库" :visible.sync="codeBaseVisible" width="50%">
			<div class="row-me row-center margin-bottom20">
				<el-select v-model="codeParams.status" placeholder="状态" class="margin-right10 width300" clearable>
					<el-option label="已使用" :value="1"></el-option>
					<el-option label="未使用" :value="0"></el-option>
				</el-select>
				<el-input v-model="codeParams.code" placeholder="请输入兑换码号" class="margin-right10 width300"></el-input>
				<el-button type="primary" @click="getPageQuery">搜索</el-button>
				<el-button type="primary" @click="clickExport">
					批量导出
				</el-button>
			</div>
			<el-table :data="tableCodeData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column prop="code" label="兑换码" align="center"></el-table-column>
				<el-table-column prop="status" label="状态" align="center">
					<template slot-scope="scope">
						{{scope.row.status?'已使用':'未使用'}}
					</template>
				</el-table-column>
				<el-table-column prop="userName" label="兑换人" align="center"></el-table-column>
				<el-table-column prop="createTime" label="兑换时间" align="center">
					<template slot-scope="scope">
						{{scope.row.validation==2?scope.row.validation:'长期有效'}}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="100" align="center">
					<template slot-scope="scope">
						<el-button type="text" @click="handleCodeLock(scope.row)">使失效</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total,sizes, prev, pager, next" :page-sizes="[30, 40, 50, 60]"
					@size-change="handleCodeSizeChange" :current-page="codeParams.pageIndex" :total="codeTotal"
					@current-change="handleCodePageChange"></el-pagination>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="codeBaseVisible = false" type="primary">关 闭</el-button>
			</span>
		</el-dialog>

		<!-- 新建科目兑换码 -->
		<el-dialog title="新建科目兑换码" :visible.sync="addVisible" width="50%">
			<el-form :model="form" label-width="100px" :rules="rules" ref="form">
				<el-form-item label="兑换码名称:" prop="title">
					<el-input v-model="form.title" placeholder="请输入" class="width400"></el-input>
				</el-form-item>
				<el-form-item label="前缀:" prop="prefix">
					<el-input v-model="form.prefix" placeholder="请输入" class="width400"></el-input>
				</el-form-item>
				<el-form-item label="数量:" prop="count">
					<el-input v-model="form.count" placeholder="请输入" class="width400"></el-input>
				</el-form-item>
				<el-form-item label="有效时间:" prop="validation">
					<el-radio-group v-model="form.validation">
						<el-radio :label="1">长期有效</el-radio>
						<el-radio :label="2">固定日期</el-radio>
					</el-radio-group>
					<div v-if="form.validation==2">
						<el-date-picker v-model="validationDate" type="datetimerange" range-separator="至" start-placeholder="开始日期"
							end-placeholder="结束日期" value-format="yyyy-MM-DD HH:mm:ss" @change="onChange">
						</el-date-picker>
					</div>
				</el-form-item>
				<el-form-item label="兑换类型:" prop="type">
					<el-select placeholder="请选择兑换类型" class="width260 margin-right10" v-model="form.type" clearable
						@change="prodectTopicArr=[]">
						<el-option label="商品兑换" :value="1"></el-option>
						<el-option label="专题兑换" :value="2"></el-option>
						<el-option label="机构兑换" :value="4"></el-option>
					</el-select>
				</el-form-item>
				<template v-if="form.type==4">
					<el-form-item label="绑定机构" prop="organId">
						<el-select placeholder="请选择绑定机构" class="width400" v-model="form.organId">
							<el-option v-for="(item,index) in organAll" :key="index" :label="item.organName"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="选择科目" prop="objectId">
						<el-select placeholder="请选择绑定机构" class="width400" v-model="form.objectId">
							<el-option v-for="(item,index) in appidData" :key="index" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</template>
				<el-form-item label="选择内容:" prop="content" v-if="form.type&&form.type!=4">
					<div class="height50 width140 row-me center-all pointer color606266" @click="clickCommodity"
						style="border: 1px dashed #8a8d93;">
						<i class="el-icon-plus margin-right10"></i><span>选择{{form.type==1?'商品':form.type==2?'专题':''}}</span>
					</div>
					<div class="row-me flex-wrap" style="width: 600px;">
						<div class="border-h5 row-me row-center margin-top10 margin-right10" v-for="(item,index) in prodectTopicArr"
							:key="index">
							<div class="flex1 line2" style="color: #7d7d7d;">
								{{item.name}}
							</div>
							<div class="text-right">
								{{item.shopTitle}}
							</div>
						</div>
					</div>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addVisible = false">取 消</el-button>
				<el-button @click="handleSave" type="primary">确 认</el-button>
			</span>
		</el-dialog>

		<el-dialog :title="form.type==1?'选择商品':form.type==2?'选择专题':''" :visible.sync="commodityVisible"
			:modal-append-to-body="false" append-to-body width="40%">
			<ProductTopic ref="ProductTopic"></ProductTopic>
			<span slot="footer" class="dialog-footer">
				<el-button @click="commodityVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleCommoditySave">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import ProductTopic from '@/components/ProductTopic';
	export default {
		components: {
			ProductTopic
		},
		data() {
			return {
				query: {
					pageNumber: 1,
					pageSize: 30
				},
				pageTotal: 0,
				organAll: [],
				tableData: [],
				dateTime: [],
				codeBaseVisible: false,
				tableCodeData: [],
				codeParams: {
					pageNumber: 1,
					pageSize: 30
				},
				tableCodeData: [],
				codeTotal: 0,
				addVisible: false,
				form: {},
				rules: {
					title: {
						required: true,
						message: '请输入兑换码名称',
						trigger: 'blur'
					},
					count: {
						required: true,
						message: '请输入数量',
						trigger: 'blur'
					},
					validation: {
						required: true,
						message: '请选择有效时间',
						trigger: 'change'
					},
					type: {
						required: true,
						message: '请选择兑换类型',
						trigger: 'change'
					},
					organId: {
						required: true,
						message: '请选择绑定机构',
						trigger: 'change'
					},
					objectId: {
						required: true,
						message: '请选择科目',
						trigger: 'change'
					}
				},
				appidData: [],
				validationDate: [],
				commodityVisible: false,
				prodectTopicArr: []
			}
		},
		mounted() {
			this.getOrganAll()
			this.getData()
			this.getAll()
		},
		methods: {
			handleCommoditySave() {
				// let arr = [...this.$refs.ProductTopic.multipleSelection, ...this.prodectTopicArr]
				// this.form.objectId = [...new Set(arr.map(JSON.stringify))].map(JSON.parse)
				this.form.objectId = null
				this.prodectTopicArr = []
				let multipleSelection = this.$refs.ProductTopic.multipleSelection
				console.log(multipleSelection, "multipleSelection")
				if (multipleSelection && multipleSelection.length != 0) {
					this.form.objectId = multipleSelection.id
					this.prodectTopicArr = [multipleSelection]
				}
				this.commodityVisible = false
			},
			clickCommodity() {
				this.commodityVisible = true
				setTimeout(() => {
					this.$refs.ProductTopic.show(this.form.type)
				})
			},
			handleSave() {
				this.$refs['form'].validate(async (valid) => {
					if (valid) {
						const res = await this.$postForm('/admin/activationCode/addBatch', this.form)
						if (res.code == 1000) {
							this.$message.success('添加成功')
							this.validationDate = []
							this.form = {}
							this.getData()
							this.addVisible = false
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			async getAll() {
				const res = await this.$get('/admin/minis/getAll')
				if (res.code == 1000) {
					this.appidData = res.data
				}
			},
			onChange(val) {
				this.form.startTime = ''
				this.form.endTime = ''
				if (val.length != 0) {
					this.form.startTime = val[0]
					this.form.endTime = val[1]
				}
			},
			//码库分页
			handleCodePageChange(val) {
				this.codeParams.pageNumber = val
				this.getPageQuery()
			},
			handleCodeSizeChange(val) {
				this.codeParams.pageSize = val
				this.getPageQuery()
			},
			//批量导出
			clickExport() {
				let params = this.codeParams
				params.pageSize = 1000000000;
				params.token = localStorage.getItem('token');
				params.appid = localStorage.getItem('appid');
				window.open(this.$host + '/admin/activationCode/export?' + this.$.getParamsString(params));
			},
			// 使失效操作
			handleLock(row) {
				this.$confirm('失效后无法恢复，该组兑换码将无法使用。已兑换的用户权益不受影响。', '提示', {
						type: 'warning'
					})
					.then(() => {
						this.$post('/admin/activationCode/cancelBatch', [row.id]).then(res => {
							if (res.code == 1000) {
								this.$message.success('操作成功')
								this.getData()
							}
						})
					})
					.catch(() => {});
			},
			//码库使失效
			handleCodeLock(row) {
				this.$confirm('失效后无法恢复，该组兑换码将无法使用。已兑换的用户权益不受影响。', '提示', {
						type: 'warning'
					})
					.then(() => {
						this.$post('/admin/activationCode/cancelBatchAll', [row.id]).then(res => {
							if (res.code == 1000) {
								this.$message.success('操作成功')
								this.getPageQuery()
							}
						})
					})
					.catch(() => {});
			},
			//码库
			clickCode(row) {
				this.codeParams.parentId = row.id
				this.codeBaseVisible = true
				this.getPageQuery()
			},
			async getPageQuery() {
				const res = await this.$get('/admin/activationCode/pageQuery', this.codeParams)
				if (res.code == 1000) {
					this.tableCodeData = res.data.list
					this.codeTotal = res.data.totalRow
				}
			},
			//搜索时间变动
			onDateChange(val) {
				this.query.startTimes = ''
				this.query.endTimes = ''
				if (val && val.length != 0) {
					this.query.startTimes = val[0]
					this.query.endTimes = val[1]
				}
			},
			//分页
			handleSizeChange(val) {
				this.query.pageSize = val
				this.getData();
			},
			handlePageChange(val) {
				this.query.pageNumber = val
				this.getData();
			},
			//获取数据
			async getData() {
				const res = await this.$get('/admin/activationCode/pageQueryParent', this.query)
				if (res.code == 1000) {
					this.tableData = res.data.list
					this.pageTotal = res.data.totalRow
				}
			},
			//获取机构
			async getOrganAll() {
				const res = await this.$postForm('/admin/messages/organAll', {
					pageNumber: 1,
					pageSize: 99999
				})
				if (res.code == 1000) {
					this.organAll = res.data.list
				}
			},
			// 触发搜索按钮
			handleSearch() {
				this.query.pageNumber = 1
				this.getData();
			},
			handleRefresh() {
				this.query = {
					pageNumber: 1,
					pageSize: 30
				}
				this.dateTime = []
				this.handleSearch()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.border-h5 {
		border: 1px solid #ccc;
		width: 260px;
		line-height: 20px;
		padding: 10px;
	}
</style>